package com.ruoyi.project.service.impl;

import com.ruoyi.project.domain.FinSubject;
import com.ruoyi.project.domain.FinSubjectMonth;
import com.ruoyi.project.mapper.FinSubjectMapper;
import com.ruoyi.project.mapper.FinSubjectMonthMapper;
import com.ruoyi.project.service.IDataSyncService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class DataSyncServiceImpl implements IDataSyncService {

    @Resource
    private FinSubjectMapper finSubjectMapper;
    @Resource
    private FinSubjectMonthMapper finSubjectMonthMapper;

    @Override
    public void syncSubjectLevel() {
        List<FinSubject> finSubjectList = finSubjectMapper.selectFinSubjectList(new FinSubject());
        Map<String,FinSubject> idMap = new HashMap<>();
        for (FinSubject finSubject : finSubjectList) {
            if (finSubject.getParentId()==null || finSubject.getParentId()==0) {
                finSubject.setSubjectLevel(1);
                idMap.put(finSubject.getId().toString(),finSubject);
            }
        }
        int level =2;
        for(int j = level;j<5;j++){
            for (FinSubject finSubject : finSubjectList) {
                if (finSubject.getParentId()!=null) {
                    FinSubject parent = idMap.get(finSubject.getParentId().toString());
                    if(parent!=null){
                        finSubject.setSubjectLevel(parent.getSubjectLevel()+1);
                        idMap.put(finSubject.getId().toString(),finSubject);
                    }
                }
            }
            level++;
        }
        for (FinSubject finSubject : finSubjectList) {
            finSubjectMapper.updateSubjectLevel(finSubject.getId(),finSubject.getSubjectLevel());
            finSubjectMonthMapper.updateLevelBySubjectId(finSubject.getId(),finSubject.getSubjectLevel());
        }
    }
}
